using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;
using System.Diagnostics;

/// 26.01.2009 - Sirul de conectare poate sa contina si - la numele serverului
///              versiunea 1.0.0.4

namespace ERPStudio
{
    public partial class FrmLogin : Form
    {
        private bool schimbatCoonString = true;
        public bool loadTabele = false;
        SqlConnection Conexiune = null;
        bool cu_baza = false;
        public FrmMainMdi mainFrm=null;
        public List<eInfoModule> lstModule = null;
        public FrmLogin(bool vcu_baza,List<eInfoModule> lst) 
        {
            lstModule = lst;
            cu_baza = vcu_baza;
            InitializeComponent();
        }
        public FrmLogin()
        {
            InitializeComponent();
        }
        public void MyTrace(String val)
        {
            Trace.WriteLine("[" + DateTime.Now.ToString() + "]" + val);
        }        
        /// <summary>
        /// returneaza sirul de conectare introdus in controale
        /// </summary>
        /// <returns></returns>
        public String GetCtrlConnString(Boolean defaultB)
        {
            String numeBaza = "master";
            if(!defaultB)
                numeBaza = this.BazaDateCB.Text;
            String conString = "Data Source=" + ctrlServer.Text + ";Initial Catalog=" + numeBaza + ";";
            if (radioButtonAuthWin.Checked == true)
                conString += "Integrated Security=True;";
            else
            {
                conString += "User ID=" + this.ctrlUtilizator.Text + ";";
                conString += "Password=" + this.ctrlParola.Text + ";";
            }
            switch (comboBoxNet.SelectedIndex)
            {
                case 1:
                    conString += "Net=dbmssocn;";
                    break;
                case 2:
                    conString += "Net=dbnmpntw;"; //pipe
                    break;
                case 0:
                    conString += "Net=dbmslpcn;";
                    break;
                case -1:
                    //daca nu a fost selectat nici un protocol merge pe TCP/IP
                    conString += "Net=dbmssocn;";
                    break;
            }
            conString += "Connection Timeout=" + numericUpDown1.Value.ToString() + ";";
            return conString;
        
        }
        private void Save() {
            try
            {
                // Get the application configuration file.*/
                System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration("ERPStudio.exe");
                // Get the connection strings section.

                ConfigurationSection section = config.GetSection("connectionStrings");
                if (section != null && section.SectionInformation.IsProtected)
                {
                    section.SectionInformation.UnprotectSection();
                }

                ConnectionStringsSection csSection = config.ConnectionStrings;
                KeyValueConfigurationCollection configSettings = config.AppSettings.Settings;
                if (configSettings["DefaultConnection"] == null)
                {
                    config.AppSettings.Settings.Add(new KeyValueConfigurationElement("DefaultConnection", "ESRPConnectionString"));
                }
                ///salveaza conexiunea selectata
                csSection.ConnectionStrings[ConexiuneCB.Text].ConnectionString = GetCtrlConnString(false);

                                
                if (section != null && !section.SectionInformation.IsProtected)
                {
                    section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
                }
                    
                config.Save(ConfigurationSaveMode.Full);   

            }
            catch (ConfigurationErrorsException err)
            {
                MessageBox.Show("Eroare configurare: " + err.ToString());
                return;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Eroare la Salvare : " + ex.Message);
            }

        }
        private void FrmLogin_Load(object sender, EventArgs e)
        {           
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration("ERPStudio.exe");

            KeyValueConfigurationCollection configSettings = config.AppSettings.Settings;
            MyTrace("Check settings for 'DefaultConnection'");
            if (configSettings["DefaultConnection"] == null)
            {
                MyTrace("Add settings for 'DefaultConnection'");
                config.AppSettings.Settings.Add(new KeyValueConfigurationElement("DefaultConnection", "ESRPConnectionString"));
                config.Save();
            }

            MyTrace("Read all connections strings");
            ConfigurationSection section = config.GetSection("connectionStrings");
            if (section.SectionInformation.IsProtected)
            {
                try
                {
                    section.SectionInformation.UnprotectSection();
                }
                catch(Exception)
                {
                    config.Sections.Remove("connectionStrings");
                }
            }

            ///incarca combo cu numele conexiunilor
            ///
            foreach (ConnectionStringSettings cs1 in config.ConnectionStrings.ConnectionStrings)
            {
                this.ConexiuneCB.Items.Add(cs1.Name);
            }
            MyTrace("Added " + ConexiuneCB.Items .Count.ToString()+ " connections strings");
            if (configSettings["DefaultConnection"] != null)
                this.ConexiuneCB.Text = configSettings["DefaultConnection"].Value.ToString();
            else
            {
                MessageBox.Show("Nu s-a definit Default Connection", "Eroare", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
         
        }

        private void LoadConnString(String idConn)
        {
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration("ERPStudio.exe");
            ///msg contine sirul de eroare
            StringBuilder msg = new StringBuilder();
            ConnectionStringSettings cs = config.ConnectionStrings.ConnectionStrings[idConn];
            if ((cs==null) || (cs.ConnectionString == string.Empty)) {
                MessageBox.Show("Nu s-a definit stringul de conectare la baza de date", "Eroare", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }                  

            Match m1 = Regex.Match(cs.ConnectionString, @"Data Source\s*=\s*(?<datasource>[\w|\d|\\|\.|\-|\,]+)\s*;");
            if (m1.Success == true)
            {
                ctrlServer.Text = m1.Groups["datasource"].ToString();
            }
            else {
                msg.Append("Sirul de conectare nu contine tagul Data Source!\n");
            }

            m1 = Regex.Match(cs.ConnectionString, @"Initial Catalog\s*=\s*(?<initcat>\w+)\s*;?");
            if (m1.Success == true)
            {
                this.BazaDateCB.Text = m1.Groups["initcat"].ToString();
            }
            else
            {
               msg.Append("Sirul de conectare nu contine tagul Initial Catalog!\n");
            }

            m1 = Regex.Match(cs.ConnectionString, @"Integrated Security\s*=\s*(?<isec>\w+)\s*;?");
            if (m1.Success == true)
            {
                if (m1.Groups["isec"].ToString().ToLower() == "true")
                {
                    radioButtonAuthWin.Checked = true;
                    radioButtonAuthSQL.Checked = false;
                }
                else
                {
                    radioButtonAuthWin.Checked = false;
                    radioButtonAuthSQL.Checked = true;
                }
            }
            else
            {
                //pune bifa pe false
                radioButtonAuthWin.Checked = false;
                radioButtonAuthSQL.Checked = true;
            }
            //daca este cu autorizare SQL


            if (radioButtonAuthSQL.Checked == true)
            {
                //citeste utilizatorul si parola
                m1 = Regex.Match(cs.ConnectionString, @"User ID\s*=\s*(?<userid>\w+)\s*;?");
                if (m1.Success == true)
                {
                    ctrlUtilizator.Text = m1.Groups["userid"].ToString();
                }
                else
                {
                    msg.Append("Sirul de conectare nu contine tagul User ID!\n");
                }
                //acum parola
                m1 = Regex.Match(cs.ConnectionString, @"Password\s*=\s*(?<passwd>\w+)\s*;");
                if (m1.Success == true)
                {
                    ctrlParola.Text = m1.Groups["passwd"].ToString();
                }
                else
                {
                    msg.Append("Sirul de conectare nu contine tagul Password!\n");
                }
                m1 = Regex.Match(cs.ConnectionString, @"Net\s*=\s*(?<net>\w+)\s*;");
                if (m1.Success == true)
                {
                    switch (m1.Groups["net"].ToString())
                    {
                        case "dbmssocn":
                            this.comboBoxNet.SelectedIndex = 1;
                            break;
                        case "dbnmpntw":
                            this.comboBoxNet.SelectedIndex = 2;
                            break;
                        case "dbmslpcn":
                            this.comboBoxNet.SelectedIndex = 0;
                            break;
                    }

                }
                else
                {
                    msg.Append("Sirul de conectare nu contine tagul Net!\n");
                }
                m1 = Regex.Match(cs.ConnectionString, @"Connection Timeout\s*=\s*(?<timeout>\w+)\s*;");
                if (m1.Success == true)
                {
                    this.numericUpDown1.Value = Convert.ToDecimal(m1.Groups["timeout"].Value);
                }
                else
                {
                    this.numericUpDown1.Value = 15;
                }
            }
            if(msg.Length != 0)
                MessageBox.Show(msg.ToString(), "Eroare", MessageBoxButtons.OK, MessageBoxIcon.Stop);

        }

        /// <summary>
        /// VERIFICA DACA se poate face o conexiune la baza de date
        /// </summary>
        /// <returns></returns>
        bool Deschide()
        {
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration("ERPStudio.exe");

            KeyValueConfigurationCollection configSettings = config.AppSettings.Settings;
            if (configSettings["DefaultConnection"] == null)
            {
                config.AppSettings.Settings.Add(new KeyValueConfigurationElement("DefaultConnection", "ESRPConnectionString"));
                config.Save();
            }
            ConnectionStringSettings cs = config.ConnectionStrings.ConnectionStrings[configSettings["DefaultConnection"].Value.ToString()];
            if ((cs == null) || (cs.ConnectionString == string.Empty))
            {
                MessageBox.Show("Nu s-a definit stringul de conectare la baza de date", "Eroare", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return false;
            }
            try
            {
                if (Conexiune == null)
                {
                    Conexiune = new SqlConnection(cs.ConnectionString);
                    Conexiune.Open();
                    Conexiune.Close();
                }
            }
            catch (SqlException ex)
            {
                FrmError err = new FrmError(ex);
                if (err.ShowDialog() != DialogResult.Ignore)
                {
                    this.DialogResult = DialogResult.Cancel;
                }
                return false;
            }
            finally
            {
                Conexiune.Dispose();
            }
            
            return true;
        
        }

        /// <summary>
        /// Handlerul butonului de confirmare
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void confirmareB_Click(object sender, EventArgs e)
        {
            DateTime dt = DateTime.Now;
            String par = "L" + dt.Month.ToString() + "Z" + dt.Day.ToString();
            if (PasswordTB.Text != par)
            {
                MessageBox.Show("Parola de control este incorecta!", "Stop");
                return;
            }
            this.Save();
            if (Deschide() == true)
            {
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void radioButtonAuthSQL_CheckedChanged(object sender, EventArgs e)
        {
            this.ctrlParola.Enabled = true;
            this.ctrlUtilizator.Enabled = true;
            this.linkLabelAltUtilizator.Enabled = false;
        }

        private void radioButtonAuthWin_CheckedChanged(object sender, EventArgs e)
        {
            this.ctrlParola.Enabled = false;
            this.ctrlUtilizator.Enabled = false;
            this.linkLabelAltUtilizator.Enabled = true ;
        }      

        private void ctrlServer_TextChanged(object sender, EventArgs e)
        {
            loadTabele = false;
        }

        private void ctrlUtilizator_TextChanged(object sender, EventArgs e)
        {
            loadTabele = false;
        }

        private void ctrlParola_TextChanged(object sender, EventArgs e)
        {
            loadTabele = false;
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }
        // If you incorporate this code into a DLL, be sure to demand FullTrust.
        [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            FrmStabilizare fStab = new FrmStabilizare(lstModule);
            fStab.ShowDialog();
        }

        private void linkLabelAltUtilizator_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            //WindowsImpersonate
            FrmWindowsLogin frm = new FrmWindowsLogin();
            frm.ShowDialog();
        }

        private void comboBox1_Enter(object sender, EventArgs e)
        {

            if (!schimbatCoonString)
                return;
            this.BazaDateCB.Items.Clear();
            using(SqlCommand cmd = new SqlCommand("", new SqlConnection(GetCtrlConnString(true))))
            {
                try
                {
                    cmd.CommandText = "sp_helpdb";
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Connection.Open();
                    SqlDataReader reader = cmd.ExecuteReader();
                    
                    while (reader.Read())
                    {
                        this.BazaDateCB.Items.Add(reader["Name"]);
                    }
                    cmd.Connection.Close();
                    cmd.Connection.Dispose();
                    schimbatCoonString = false;
                }
                catch (SqlException ex)
                {
                    if (ex.Number != 18456)
                        MessageBox.Show("Procedura eronata: " + ex.Message,"Eroare",MessageBoxButtons.OK,MessageBoxIcon.Stop);
                    else
                        MessageBox.Show("User sau parola eronata! Nu pot obtine informatii despre bazele de date existente!","Eroare",MessageBoxButtons.OK,MessageBoxIcon.Stop);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Procedura eronata: " + ex.Message);
                }

            }
        }

        private void ctrlServer_TextChanged_1(object sender, EventArgs e)
        {
            schimbatCoonString = true;
            AplicaB.Enabled = true;
        }

        private void ConexiunecomboBox_TextChanged(object sender, EventArgs e)
        {
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration("ERPStudio.exe");

            KeyValueConfigurationCollection configSettings = config.AppSettings.Settings;
            if (configSettings["DefaultConnection"] == null)
            {
                config.AppSettings.Settings.Add(new KeyValueConfigurationElement("DefaultConnection", this.ConexiuneCB.Text));
            }
            configSettings["DefaultConnection"].Value = this.ConexiuneCB.Text;
            
            config.Save();
        }

        private void ConexiunecomboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ConexiuneCB.Text!=String.Empty)
                LoadConnString(ConexiuneCB.Text);
        }
        /// <summary>
        /// Handlerul butonului care aplica modificarile din sirul de conectare curent
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void aplicaB_Click(object sender, EventArgs e)
        {
            DateTime dt = DateTime.Now;
            String par = "L" + dt.Month.ToString() + "Z" + dt.Day.ToString();
            if (PasswordTB.Text != par)
            {
                MessageBox.Show("Parola de control este incorecta!", "Stop");
                return;
            }

            this.Save();
            if (!Deschide())
            {
                MessageBox.Show("Valori incorecte!\nConectare imposibila la baza de date!", "Eroare", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
            AplicaB.Enabled = false;
        }
    }
}